<script lang="ts">
export default {
    name: 'DynamicTable'
};
</script>

<script lang="ts" setup name="DynamicTable">
import { computed, toRefs, ref, watch, nextTick, withDefaults } from 'vue';
// import type { ElementAttrs } from '@vue/runtime-dom';
// import type {} from 'dom';
import type { Column } from './index';
// swiper@8.4.3
import Swiper, { Autoplay, type SwiperOptions } from 'swiper';
// import { Swiper as SwiperInstance } from 'swiper';
import 'swiper/css';

Swiper.use([Autoplay]);

const props = withDefaults(
    defineProps<{
        columns: Column[];
        oddBg?: string;
        evenBg?: string;
        headBg?: string;
        headHeight?: string;
        dataList?: Record<string, any>[];
        borderColor?: string;
        options?: SwiperOptions;
    }>(),
    {
        columns: () => [],
        oddBg: '',
        evenBg: '',
        headBg: 'linear-gradient(to bottom, rgba(17, 36, 47, 0.9), rgba(15, 39, 52, 0.6), rgba(14, 61, 75, 0.45), rgba(0, 240, 255, 0.22))',
        headHeight: '40px',
        dataList: () => [],
        borderColor: '#075056',
        options: () => ({})
    }
);

const {
    columns,
    oddBg,
    evenBg,
    headBg,
    headHeight,
    dataList,
    borderColor,
    options
} = toRefs(props);

const defaultOptions: SwiperOptions = {
    slidesPerView: 'auto',
    direction: 'vertical',
    speed: 2000,
    loop: true,
    autoplay: {
        delay: 0,
        stopOnLastSlide: false,
        disableOnInteraction: false,
        pauseOnMouseEnter: true
    }
    // freeMode: true
    // on: {
    //     click: (...rest) => {
    //         console.log(rest);
    //     }
    // }
};
let swiper: Swiper | null = null;
const scrollerItemView = ref<HTMLDivElement | null>(null);

const initSwiper = () => {
    if (swiper) {
        // 销毁对象
        swiper.destroy();
        swiper = null;
    }
    nextTick(() => {
        if (scrollerItemView.value) {
            const parentH = scrollerItemView.value.offsetHeight;
            let childrenH = 0;
            scrollerItemView.value
                .querySelectorAll('.swiper-slide')
                .forEach((el) => {
                    childrenH += (el as HTMLDivElement).offsetHeight;
                });
            // console.log(
            //     scrollerItemView.value,
            //     scrollerItemView.value.querySelectorAll('.swiper-slide')
            // );
            if (childrenH > parentH) {
                swiper = new Swiper(
                    scrollerItemView.value,
                    Object.assign(defaultOptions, options.value)
                );
                // this.swiper.el.onmouseover = () => {
                //     this.swiper.autoplay.stop();
                // };
                // this.swiper.el.onmouseleave = () => {
                //     this.swiper.autoplay.start();
                // };
            }
        }
    });
};

const gridColumns = computed(() => {
    const arr: (string | number)[] = [];
    props.columns.forEach((item) => {
        if (item.width) {
            arr.push(item.width);
        } else {
            arr.push('1fr');
        }
    });
    return arr.join(' ');
});

watch(
    () => dataList,
    () => {
        initSwiper();
    },
    {
        deep: true,
        immediate: true
    }
);
</script>

<template>
    <div
        class="dynamic-table-container"
        :style="{ '--border_color': borderColor }"
    >
        <!-- 表头 -->
        <div
            class="table-header"
            :style="{
                background: headBg,
                height: headHeight,
                gridTemplateColumns: gridColumns
            }"
        >
            <div v-for="(col, index) in columns" :key="index" class="item">
                {{ col.label }}
            </div>
        </div>
        <!-- 表内容 -->
        <div
            ref="scrollerItemView"
            class="table-body swiper swiper-container-free-mode"
            :style="{ height: `calc(100% - ${headHeight})` }"
        >
            <div class="swiper-wrapper">
                <!-- 渲染表格的 每一行 -->
                <div
                    v-for="(item, index) in dataList"
                    :key="index"
                    class="swiper-slide swiper-grid"
                    :style="{
                        backgroundColor: index % 2 !== 0 ? evenBg : oddBg,
                        gridTemplateColumns: gridColumns
                    }"
                    @click.stop="
                        () => $emit('rowClick', { row: item, rowIndex: index })
                    "
                >
                    <slot name="row" :row="item">
                        <!-- 渲染某行的 每一列-->
                        <div
                            v-for="(col, idx) in columns"
                            class="cell"
                            :key="idx"
                            @click.stop="
                                () =>
                                    $emit('cellClick', {
                                        col,
                                        row: item,
                                        colIndex: idx,
                                        rowIndex: index
                                    })
                            "
                        >
                            <!-- 1.1.1 自定义卡槽 -->
                            <slot :name="col.field" :row="item">{{
                                item[col.field]
                            }}</slot>
                        </div>
                    </slot>
                </div>
            </div>
        </div>
    </div>
</template>

<style>
.swiper-container-free-mode .swiper-wrapper {
    transition-timing-function: linear;
}
</style>

<style scoped lang="scss">
.dynamic-table-container {
    height: 100%;
    width: 100%;
    border-top: 1px solid var(--border_color);
    overflow: hidden;
    .table-header {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        height: vh(40);
        position: relative;
        z-index: 1;
        .item {
            display: inline-grid;
            height: inherit;
            justify-items: center;
            align-items: center;
            font-size: vh(14);
            color: #ffffff;
            &:first-child {
                border-left: 1px solid var(--border_color);
            }
            &:last-child {
                border-right: 1px solid var(--border_color);
            }
        }
    }

    .table-body {
        height: calc(100% - vh(40));
        border: 1px solid var(--border_color);
        border-right: none;
        .swiper-wrapper {
            .swiper-slide {
                display: grid;
                grid-template-columns: repeat(4, 1fr);
                min-height: vh(40);
                height: auto;
                .cell {
                    display: inline-grid;
                    justify-content: center;
                    align-items: center;
                    border: 1px solid var(--border_color);
                    margin-left: -1px;
                    margin-top: -1px;
                    color: #ffffff;
                    font-size: vh(14);
                }
            }
        }
    }
}
</style>
